import * as fs from 'fs';
import * as path from 'path';

const needDeleteSuffix = ['.d.ts', 'spec.js', 'spec.js.map'];
const needCopyFiles = [
  {from: './src/state/files/', to: './dist/src/state/files/'},
  {from: './src/collection.json', to: './dist/src/collection.json'},
  {from: './src/state/schema.json', to: './dist/src/state/schema.json'},
  {from: './README.md', to: './dist/README.md'},
  {from: './package.json', to: './dist/package.json'},
];

let distFiles = fs.readdirSync('./dist', {withFileTypes: true, recursive: true});
// 删除不需要的文件
for (let file of distFiles) {
  for (let suffix of needDeleteSuffix) {
    if (file.name.endsWith(suffix)) {
      fs.rmSync(`${file.parentPath}/${file.name}`);
    }
  }
}
for (let file of needCopyFiles) {
  copyFile(file.from, file.to);
}

function copyFile(from: string, to: string) {
  let fromPath = path.resolve(from);
  let toPath = path.resolve(to);
  if (!fs.existsSync(fromPath)) return;
  let stats = fs.statSync(fromPath);
  if (stats.isFile()) {

    fs.copyFileSync(fromPath, toPath);
  } else if (stats.isDirectory()) {
    fs.mkdirSync(toPath, {recursive: true});
    let files = fs.readdirSync(fromPath, {withFileTypes: true, recursive: true});
    for (let file of files) {
      let filePath = path.resolve(`${file.parentPath}/${file.name}`);
      let relativePath = path.relative(fromPath, filePath);
      let fileToPath = path.resolve(`${toPath}/${relativePath}`);
      copyFile(filePath, fileToPath);
    }
  }
}
